package cn.edu.jxnu.sse.servlet;

import cn.edu.jxnu.sse.dao.BookDao;
import cn.edu.jxnu.sse.entity.Book;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(name = "BookServlet",urlPatterns = "/book")
public class BookServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/json; charset=utf-8");    // 设置response的编码及
        request.setCharacterEncoding("utf-8");
        String bookName = request.getParameter("bookName");
        BookDao bookDao = new BookDao();
        List<Book> ret = bookDao.findByName(bookName);
        ObjectMapper mapper = new ObjectMapper();
        String resJSON = mapper.writeValueAsString(ret);
        PrintWriter out = response.getWriter();
        out.write(resJSON);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
        /*request.setCharacterEncoding("utf-8");
        String bookName = request.getParameter("bookName");
        BookDao bookDao = new BookDao();
        List<Book> ret = bookDao.findByName(bookName);
        request.setAttribute("books",ret);
        RequestDispatcher disp = request.getRequestDispatcher("books.jsp");
        disp.forward(request,response);*/
    }
}
